﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using MOJsdk;
using System.Collections.ObjectModel;
using System.Threading;
using System.Windows.Threading;

namespace MOJ
{
    /// <summary>
    /// Interaction logic for Control_ImportMovies.xaml
    /// </summary>
    public partial class Control_ImportMovies : UserControl
    {
        private Control_MovieDetails _details;
        private ObservableCollection<MOJMovie> _movies;
        private int _Selected;
        private bool _loading = false;

        public Control_ImportMovies()
        {
            InitializeComponent();
            INI();
        }

        #region INIcialization
        private void INI()
        {
            INIVisualElements();
            INIEvents();
        }
        private void INIVisualElements()
        {
            _details = new Control_MovieDetails();
            _listView_Titles.SelectionMode = SelectionMode.Single;
            _listView_Titles.ItemsSource = null;
            _movies = new ObservableCollection<MOJMovie>();
            _Selected = -1;

            _dockPanel.Children.Add(_details);
            _ForegroundGrid.Visibility = System.Windows.Visibility.Hidden;

            _Grid.ApplyStyle("0101013");
            _listView_Titles.ApplyStyle("0101015");
            _dockPanel.ApplyStyle("0101014");
            _ForegroundGrid.ApplyStyle("0101126");
            _ProgBar.ApplyStyle("0101127");
        }
        private void INIEvents()
        {
            _listView_Titles.SelectionChanged += SelectedMovieChanged;
            this.Loaded += ElementLoaded;
        }
        #endregion

        public void UpdateList()
        {
            noArgs th = new noArgs(UpdateListAsync);
            th.BeginInvoke(null, null);
        }
        private void UpdateListAsync()
        {
            if (_loading)
                return;

            _loading = true;

            try
            {
                SetUpdateStatus(true);

                List<string> list = new List<string>(GlobalVars.TheHost.LoadMoviesCodes());
                foreach (var v in list)
                {
                    MOJMovie m = new MOJMovie(v);
                    DispatcherOperation op = this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate
                    {
                        _movies.Add(m);
                        SetProgess(_movies.Count, list.Count);
                    });
                    while (op.Status != DispatcherOperationStatus.Completed) { }
                }


                this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate
                {
                    _listView_Titles.ItemsSource = null;
                    _movies = new ObservableCollection<MOJMovie>(_movies.OrderBy(m => m.MovieTitle));
                    _listView_Titles.ItemsSource = _movies;
                });

                SetUpdateStatus(false);

            }
            catch (Exception ex)
            {
                GlobalVars.TheHost.ReportError(new ErrorReporter()
                {
                    ErrorCode = "",
                    ErrorDetails = ex.ToString(),
                    ErrorMessage = "Error loading movies",
                });
            }

            _loading = false;
        }

        private void SetUpdateStatus(bool value)
        {
            DispatcherOperation op = this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate
            {
                if (value)
                {
                    _ForegroundGrid.Visibility = System.Windows.Visibility.Visible;
                    _listView_Titles.ItemsSource = null;
                    _movies = new ObservableCollection<MOJMovie>();
                    _listView_Titles.ItemsSource = _movies;
                    _ProgBar.Value = 0;
                }
                else
                {
                    _ForegroundGrid.Visibility = System.Windows.Visibility.Hidden;
                    TrySelectMovie(_Selected);
                }
            });
            while (op.Status != DispatcherOperationStatus.Completed) { }
        }
        private void SelectedMovieChanged(object sender, SelectionChangedEventArgs e)
        {
            if (_movies == null || _movies.Count == 0)
                return;

            _Selected = _listView_Titles.SelectedIndex;

            if (_Selected == -1)
            {
                _details.UnLoadMovie();
                GlobalVars.TheHost.sv_SelectedMovie = "NULL";
            }
            else
            {
                string code = _movies[_Selected].MovieCode;
                _details.LoadMovie(code);
                GlobalVars.TheHost.sv_SelectedMovie = code;
            }
        }
        private void ElementLoaded(object sender, RoutedEventArgs e)
        {
            UpdateList();
        }

        public void TrySelectMovie(int index)
        {
            if (_listView_Titles.Items.Count > index)
            {
                _listView_Titles.SelectedIndex = index;

                if(index != -1)
                    _listView_Titles.ScrollIntoView(_listView_Titles.Items[index]);
            }
            else
            {
                _listView_Titles.SelectedIndex = -1;
                GlobalVars.TheHost.sv_SelectedMovie = "NULL";
            }
        }
        public void SetProgess(int Value, int Total)
        {
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate
            {
                _ProgBar.Maximum = Total;
                _ProgBar.Value = Value;
            });
        }

        private delegate void ThreadHandler(int index);
        private delegate void noArgs();
    }
}
